package org.iqiyi.sharding;


import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author huQi
 * @email
 * @data 2021/1/20 14:19
 */
@Component
public class ShardingTableConfig implements PreciseShardingAlgorithm<Long> {
    /**
     * 在开发的环境中一定不要用随机数来决定是在哪个表，会出现无法准确的定位表的情况
     */
    @Override
    public String doSharding(Collection<String> tables, PreciseShardingValue<Long> preciseShardingValue) {
        // 分片字段值
        Long value = preciseShardingValue.getValue();
        // 现在算法是:%2 求余如果是0则ds0.xmjbq_user,如果是1则ds0.xmjbq_user。但是由于id是字符串而且是很长的，所以截取最后一位然后转为Integer类型再求余
        if (value % 2 == 0) {
            List<String> list = tables.stream().filter(s -> s.indexOf("2") > 0).collect(Collectors.toList());
            return list.get(0);
        } else {
            List<String> list = tables.stream().filter(s -> s.indexOf("1") > 0).collect(Collectors.toList());
            return list.get(0);
        }
    }
}